<?php

namespace App\Listeners;

use App\Common\Constant\Params;
use App\Events\OrderEmployed;
use App\Events\OrderSuccess;
use App\Models\MasterStatistic;
use App\Models\MerchantOrderNum;
use App\Models\Order;
use App\Models\OrderStatus;
use App\Notifications\OrderNotifications\OrderEmployedNotification;
use App\Notifications\OrderNotifications\OrderSuccessNotification;
use App\Services\ISystemTaskService;
use DB;
use Illuminate\Cache\Events\CacheHit;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

class OrderSuccessListener implements ShouldQueue
{

    use InteractsWithQueue;

    public $queue = 'order';

    public $tries = 3;

    public $timeout = 30;

    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  CacheHit  $event
     * @return void
     */
    public function handle(OrderSuccess $event)
    {
        $order = Order::find($event->order_id);
        if(!$order){
            throw new \Exception('miss order');
        }

        $ret = resolve(ISystemTaskService::class)->orderMoneyArrive($order->id);
        if(!$ret){
            throw new \Exception('order money arrive fail');;
        }

        $ret = MerchantOrderNum::where([
            'me_id'=>$order->merchant_id,
            'order_type'=>Params::ORDER_TYPE_OFFER
        ])->take(1)->update([
            'wait_evaluate'=>DB::raw('wait_evaluate+1')
        ]);
        if(!$ret){
            throw new \Exception('merchant order num update fail');
        }

        $ret = MasterStatistic::where([
           'master_id'=> $order->master_id
           ])->take(1)->update([
           'points'=>DB::raw('points+1')
           ]);
           if(!$ret){
            throw new \Exception('merchant order num update fail');
        }
        $order->master->notify(new OrderSuccessNotification($order));
    }

    public function failed(OrderSuccess $event, \Exception $exception)
    {
        //
    }
}
